import { Toast } from "../components/Toast";
import LocalValues, { LocalKey } from "../data/LocalValues";
import { EventReport } from "./EventReport";
import MyFetch from "./MyFetch";

//重试次数
const RETRY_COUNT = 1;
//重试间隔
const RETRY_INTERVAL = 2000;

export const enum ABTestKey {
    bannerShowState = 'bannerShowState',
    interAdOpenLv = 'interAdOpenLv',
}

const defaultAbValue = {
    [ABTestKey.bannerShowState]: 1,
    [ABTestKey.interAdOpenLv]: 3,
}

export class ABTest {
    private static _url: string = 'http://bi.triwingames.com/api/getAbParams';
    private static _params: IAbTestParams = null;
    private static _data: IAbTestData = null;

    //登录后调用
    public static async init(params: IAbTestParams) {
        this._params = params;
        console.log('### ABTest init', params.uid, params.apiKey);
        await this.request();
        // Toast.show("ABTest banner: "+ this.getKey(ABTestKey.bannerShowState));
    }

    public static async request() { 
        if (!this._params) {
            console.log('### ABTest request error, params is null');
            return;
        }
        const res = await this.request2();

        console.log('### ABTest request', JSON.stringify(res));
        if(res && res.data){
            console.log('### ABTest request', "线上参数");
            this._data = res.data;
            // LocalValues.setObject(LocalKey.abTestData, this._data);

            EventReport.pull_ab_param(this.handleReportData(res.data.params));
            this.assignValue(res.data);

            LocalValues.setObject(LocalKey.abTestData, this._data);

        }else{
            // console.log('### ABTest request', "本地参数");
            this._data = LocalValues.getObject(LocalKey.abTestData);
            console.log('### ABTest request', "本地参数", JSON.stringify(this._data));
        }
    }

    private static async request2(retryTimes: number = 0){
        const res = await MyFetch.postExternal(this._url, this._params);
        console.log('### ABTest request2', JSON.stringify(res), 'retryTimes:', retryTimes);
        
        if (!res.data?.miss_params?.length) {
            return res;
        }

        if (retryTimes >= RETRY_COUNT) {
            console.log('### ABTest request2 error, retry times exceeded');
            return res;
        }

        console.log('### ABTest request2 waiting for retry...');
        await new Promise(resolve => setTimeout(resolve, RETRY_INTERVAL));
        
        return await this.request2(retryTimes + 1);
    }

    private static assignValue(data: IAbTestData) {
        const miss_params = data.miss_params;
        if(!data.params){
            data.params = {};
        }
        let reportData = {};
        for(let i = 0; i < miss_params.length; i++){
            const key = miss_params[i];
            data.params[key] = defaultAbValue[key].toString();
            reportData[`params.${key}`] = defaultAbValue[key].toString();
        }
        EventReport.ab_test_assign(reportData);
    }

    private static handleReportData(oriObj: { [key: string]: string }){
        const reportData = {};
        if(!oriObj){
            return reportData;
        }
        for(let key in oriObj){
            reportData[`params.${key}`] = oriObj[key];
        }
        return reportData;
    }
    
    public static getKey(key: ABTestKey) {
        let value:number;
        if(this._data?.params?.[key] !== undefined){
            value = Number(this._data.params[key]);
        }else{
            value = defaultAbValue[key];
        }
        
        EventReport.ab_param_use({
            [`params.${key}`] : value.toString(),
        });

        return value;
        
    }


    
}

//请求参数
export interface IAbTestParams {
    apiKey: string;
    uid: string;
}

//返回数据
export interface IAbTestData {
    miss_params: string[];
    params: {
        [key: string]: string;
    } | null;
    force_params: {
        [key: string]: string;
    } | Array<any>;
}

